package Solution.problem080.RemoveDuplicatesFromSortedArray2;

import org.junit.Test;

/**
 * @program Leetcode
 * @description:
 * Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
 *
 * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
 *
 * 题干大意：就是给你一个排序的数组，其中的元素最多存在两个，如果多余两个就删除多的
 * 注意的点：
 *         1、O(1)的额外空间
 *         2、要修改数组
 *         3、不关心超出部分数组中的值是什么
 * @author: lishangsheng
 * @create: 2019/06/15 12:04
 */
public class Solution {
    public int removeDuplicates(int[] nums) {

        /** 边界控制*/
        if(nums==null||nums.length==0){
            return 0;
        }

        int preNum=nums[0];
        int index=1;
        int preCount=1;
        int length=nums.length;

        for(int i=index;i<length;){
            int value=nums[i];
            /**  新值*/
            if(value!=preNum){
                preNum=value;
                preCount=1;
                i++;
            }else {
                /** 老值*/
                if(preCount>=2){
                    length--;
                    removeValue(nums,i);
                }else {
                    preCount++;
                    i++;
                }
            }
        }
        return length;

    }

    private void removeValue(int[] num,int index){
        for(int i=index;i<num.length-1;i++){
            num[i]=num[i+1];
        }
    }

    @Test
    public void test(){
/*        int[] nums=new int[]{1,1,1,2,2,3};
        System.out.println(removeDuplicates(nums));*/
        int[] nums2=new int[]{0,0,1,1,1,1,2,3,3};
        System.out.println(removeDuplicates2(nums2));
    }

    /**
     * 最短代码解
     * @param nums
     * @return
     */
    public int removeDuplicates2(int[] nums) {
        int len = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i < 2 || (nums[i] != nums[len - 1] || nums[i] != nums[len - 2])) {
                nums[len++] = nums[i];
            }
        }
        return len;
    }

}
